package acme.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;

import acme.entity.FetchAppResponse;

public class TestAPI {

	public static void main(String[] args)
	{
		//masheryAPICall();
		masheryAPIFetchAccessToken( "nddqemeym6zpypc4h3pve2bf","XcA6qN62x6hW3Mym3W6tHcuW",  "http://developer.wideworldofacme.com/io-docs/oauth2callback", "5hc2rqun9dkq2cxcs6kjw8rz");
	}
	
	public static String masheryAPIFetchApp(String clientID, String areaID)
	{
		
		String id = "1";
		String method = "oauth2.fetchApplication";
		

		
		String serviceKey = "yebcae8cahnrpxz68fxck2kj";
		String apiKey = "yaa826zy4mswa33ytw6ynx3g";
		String apiSecret = "XGaEBwaqVY";
		String sig = "";
		try {
			sig = Util.generateSignature(apiKey,apiSecret);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String jsonBody = "{\"id\": \"" + id 
				+ "\", \"jsonrpc\": \"2.0\", \"method\": \""+ method +
				"\", \"params\": {\"client\": { \"client_id\": \"" + clientID +
				"\"},\"service_key\": \"" + serviceKey + 
				"\",\"response_type\": null,\"uri\": null}}";
		
		String url = "https://api2.mashery.com/v2/json-rpc/" +
				areaID + "?apikey=" + apiKey + "&sig=" + sig;
		
		 try {
			 System.out.println(url);
			 System.out.println(jsonBody);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost postRequest = new HttpPost(url);
 

		
		StringEntity input = new StringEntity(jsonBody);
		input.setContentType("application/json");
		postRequest.setEntity(input);
 
		HttpResponse response = httpClient.execute(postRequest);
 
		System.out.println(response.toString());
		if (response.getStatusLine().getStatusCode() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
				+ response.getStatusLine().getStatusCode());
		}
 
		BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
 
		String output;
		String jsonResponse = "";
		System.out.println("Output from Server .... \n");
		while ((output = br.readLine()) != null) {
			System.out.println(output);
			jsonResponse = jsonResponse + output;
		}
 
		int idStart = jsonResponse.indexOf("{\"id");
		int idEnd = jsonResponse.indexOf('"', idStart+5);
		String idString = jsonResponse.substring(idStart+6,idEnd-1);
		
		 
		int nameStart = jsonResponse.indexOf(",\"name");
		int nameEnd = jsonResponse.indexOf('"', nameStart+9);
		String nameString = jsonResponse.substring(nameStart+9,nameEnd);
		
		System.out.println("ID = " + idString);
		System.out.println("App Name = " + nameString);
		
		
		httpClient.getConnectionManager().shutdown();
		
		return nameString;
 
	  } catch (MalformedURLException e) {
 
		e.printStackTrace();
		return "";
 
	  } catch (IOException e) {
 
		e.printStackTrace();
		return"";
 
	  }
 
	}
	
	public static String masheryAPIFetchAuthCode(String clientID, String areaID, String redirectURI, String scope)
	{
		
		String id = "1";
		String method = "oauth2.createAuthorizationCode";
		

		
		String serviceKey = "yebcae8cahnrpxz68fxck2kj";
		String apiKey = "yaa826zy4mswa33ytw6ynx3g";
		String apiSecret = "XGaEBwaqVY";
		String sig = "";
		try {
			sig = Util.generateSignature(apiKey,apiSecret);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		

		String jsonBody = "{\"id\": \"" + id 
				+ "\", \"jsonrpc\": \"2.0\", \"method\": \""+ method +
				"\", \"params\": [\""+ serviceKey + "\",{\"client_id\": \"" + clientID +
				"\"},{\"redirect_uri\": \"" + redirectURI + 
				"\"},\"all_scope\", \"" + scope + "\"],\"id\": 1}";
		
		String url = "https://api2.mashery.com/v2/json-rpc/" +
				areaID + "?apikey=" + apiKey + "&sig=" + sig;
		
		 try {
			 System.out.println(url);
			 System.out.println(jsonBody);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost postRequest = new HttpPost(url);
 

		
		StringEntity input = new StringEntity(jsonBody);
		input.setContentType("application/json");
		postRequest.setEntity(input);
 
		HttpResponse response = httpClient.execute(postRequest);
 
		System.out.println(response.toString());
		if (response.getStatusLine().getStatusCode() != 200) {
			throw new RuntimeException("Failed : HTTP error code : "
				+ response.getStatusLine().getStatusCode());
		}
 
		BufferedReader br = new BufferedReader(
                        new InputStreamReader((response.getEntity().getContent())));
 
		String output;
		String jsonResponse = "";
		System.out.println("Output from Server .... \n");
		while ((output = br.readLine()) != null) {
			System.out.println(output);
			jsonResponse = jsonResponse + output;
		}
 
		int codeStart = jsonResponse.indexOf("{\"code");
		int codeEnd = jsonResponse.indexOf('"', codeStart+9);
		String codeString = jsonResponse.substring(codeStart+9,codeEnd);
		
		 
		int nameStart = jsonResponse.indexOf(",\"name");
		int nameEnd = jsonResponse.indexOf('"', nameStart+9);
		String nameString = jsonResponse.substring(nameStart+9,nameEnd);
		
		System.out.println("code = " + codeString);
		//System.out.println("App Name = " + nameString);
		
		
		httpClient.getConnectionManager().shutdown();
		
		return codeString;
 
	  } catch (MalformedURLException e) {
 
		e.printStackTrace();
		return "";
 
	  } catch (IOException e) {
 
		e.printStackTrace();
		return"";
 
	  }
 
	}
	
	

	@SuppressWarnings("finally")
	public static String masheryAPIFetchAccessToken(String clientID, String clientSecret, String redirectURI, String authCode)
	{
		
		String id = "1";
		String method = "oauth2.createAuthorizationCode";
		

		
		String serviceKey = "yebcae8cahnrpxz68fxck2kj";
		String apiKey = "yaa826zy4mswa33ytw6ynx3g";
		String apiSecret = "XGaEBwaqVY";
		String sig = "";
		try {
			sig = Util.generateSignature(apiKey,apiSecret);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//curl -v -u nddqemeym6zpypc4h3pve2bf:XcA6qN62x6hW3Mym3W6tHcuW -d 
		//'client_id= nddqemeym6zpypc4h3pve2bf&redirect_uri=http%3A%2F%2Fdeveloper.wideworldofacme.com%2Fio-docs%2Foauth2callback&
		//code=3djeyaz4ekpdvw6zc9s8ubfh&grant_type=authorization_code' 
		//'http://acme.api.mashery.com/acmeoauth/demo/token'

		//String url = "\'client_id= " + clientID + "&redirect_uri=" + redirectURI + "&code=" +authCode + "&grant_type=authorization_code\' \' http://acme.api.mashery.com/acmeoauth/demo/token\'";

		
        DefaultHttpClient dhttpclient = new DefaultHttpClient();

        String username = clientID;
        String password = clientSecret;
        String host = "acme.api.mashery.com";
        String uri = "http://acme.api.mashery.com/acmeoauth/demo/token";
        String codeString = "";
        try
        {
            dhttpclient.getCredentialsProvider().setCredentials(new AuthScope(host, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
            HttpPost dhttppost = new HttpPost(uri);

            
            
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            
            params.add(new BasicNameValuePair("client_id", clientID));
            params.add(new BasicNameValuePair("redirect_uri", redirectURI));
            params.add(new BasicNameValuePair("code", authCode));
            params.add(new BasicNameValuePair("grant_type", "authorization_code"));

            
            
            dhttppost.setEntity(new UrlEncodedFormEntity(params));
            dhttppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            
            System.out.println("executing request " + dhttppost.getRequestLine());
            HttpResponse dresponse = dhttpclient.execute(dhttppost);

    		BufferedReader br = new BufferedReader(
                    new InputStreamReader((dresponse.getEntity().getContent())));

	String output;
	String jsonResponse = "";
	System.out.println("Output from Server .... \n");
	while ((output = br.readLine()) != null) {
		System.out.println(output);
		jsonResponse = jsonResponse + output;
	}
	
	int codeStart = jsonResponse.indexOf(",\"access_token");
	int codeEnd = jsonResponse.indexOf('"', codeStart+20);
	codeString = jsonResponse.substring(codeStart+17,codeEnd);
	
       System.out.println("AuthCode : " + codeString);
       return codeString;
      
	
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            dhttpclient.getConnectionManager().shutdown();
            return codeString;
        }
        
		
	  
 
	}
	
	}

